package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.personal.param.*;
import com.fzg.common.model.personal.result.DeliverRecordResult;
import com.fzg.common.model.personal.result.DeliverRecordResultItem;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.*;
import com.fzg.mapper.*;
import com.fzg.service.ResumeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fzg
 * @since 2022-03-26
 */
@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements ResumeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ResumeMapper resumeMapper;

    @Autowired
    private UserEnterpriseRecruitMapper userEnterpriseRecruitMapper;

    @Autowired
    private RecruitmentEnterpriseMapper recruitmentEnterpriseMapper;

    @Autowired
    private RecruitmentInforMapper recruitmentInforMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private UserJobMapper userJobMapper;

    @Autowired
    private MessageMapper messageMapper;


    /**
     * 查询当前登陆的用户的简历信息
     *
     * @param param 参数类
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper queryLoginUserResume(QueryLoginUserResume param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        ArrayList<Object> list = new ArrayList<>();
        if (user != null){
            if (user.getResumeAid() != null){
                Resume resume = resumeMapper.selectById(user.getResumeAid());
                list.add(resume);
            }else {
                list.add(new Resume());
            }

            list.add(user);
            return ResponseWrapper.markSuccess(list);
        }else {
            User user1 = userMapper.selectById(param.getUserAid());
            if (user1.getResumeAid() != null){
                Resume resume = resumeMapper.selectById(user1.getResumeAid());
                list.add(resume);
            }else {
                list.add(new Resume());
            }
            list.add(user1);
            return ResponseWrapper.markSuccess(list);
        }


    }

    /**
     * 保存简历
     *
     * @param param 参数类
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper saveResume(SaveResumeParam param) {
        Resume resume = new Resume();
        resume.setName(param.getName());
        resume.setSex(param.getSex());
        resume.setCurrentIdentity(param.getCurrentIdentity());
        resume.setAvatar(param.getResumeAvatar());
        try {
            resume.setBirth(ToolForDateTime.stringToDate(param.getBirth()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        resume.setHukou(param.getHukou());
        resume.setCity(param.getCity());
        resume.setOutlook(param.getOutlook());
        resume.setPhone(param.getPhone());
        resume.setEmail(param.getEmail());
        resume.setHuntjobState(param.getJobState());
        resume.setExpectWork(param.getExpectWork());
        resume.setExpectIndustry(param.getExpectIndustry());
        resume.setExpectCity(param.getExpectWorkAddress());
        resume.setExpectSalary(param.getExpectSalary());
        resume.setHighestEducation(param.getHighestEducation());
        resume.setSchool(param.getSchool());
        resume.setMajor(param.getMajor());
        resume.setCompanyName(param.getCompanyName());
        resume.setCompanyType(param.getCompanyType());
        resume.setCompanyPosition(param.getCompanyPosition());
        resume.setInternshipWorkSalary(param.getInternshipSalary());
        resume.setInternshipWorkDescription(param.getInternshipDescription());
        resume.setProjectName(param.getProjectName());
        resume.setProjectDescription(param.getProjectDescription());
        resume.setEnglishLevel(param.getEnglishLevel());
        resume.setSkillDescription(param.getSkill());
        resume.setCertificate(param.getCertificate());
        resume.setPersonalAdvantange(param.getSelfAdvantang());
        resume.setSelfEvaluation(param.getSelfEvaluate());

        int insert = resumeMapper.insert(resume);
        if (insert > 0){
            // 让简历表与当前用户相连
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
            Resume resume1 = resumeMapper.selectOne(new LambdaQueryWrapper<Resume>().orderByDesc(Resume::getAid).last("limit 1"));
            userMapper.updateById(new User(){{
                setAid(user.getAid());
                setName(user.getName());
                setPassword(user.getPassword());
                setAccountNumber(user.getAccountNumber());
                setPhone(user.getPhone());
                setEmail(user.getEmail());
                setGender(user.getGender());
                setIdentityNumber(user.getIdentityNumber());
                setMaritalStatus(user.getMaritalStatus());
                setWorkExperience(user.getWorkExperience());
                setCreateTime(user.getCreateTime());
                setIsAdmin(user.getIsAdmin());
                setAddress(user.getAddress());
                setAvatar(user.getAvatar());
                setSchool(user.getSchool());
                setResumeAid(resume1.getAid());
                setResumeUrl(param.getResumeUrl());
            }});
            // 再把原来的简历删了
            if (user.getResumeAid() != null){
                resumeMapper.deleteById(user.getResumeAid());
            }
            return ResponseWrapper.markCustomSuccess("简历保存成功！");
        }else {
            return ResponseWrapper.markCustomError("简历保存失败！");
        }

    }

    /**
     * 判断当前登录的用户是否有简历
     *
     * @param param 参数类
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper checkHaveResume(CheckHaveResume param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user.getResumeUrl() != null || user.getResumeAid() != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 投递简历
     *
     * @param param 参数类
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper deliverResume(DeliverResume param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));

        int insert = userEnterpriseRecruitMapper.insert(new UserEnterpriseRecruit() {{
            setUserAid(user.getAid());
            setEnterpriseRecruitAid(param.getCompanyRecruitAid());
        }});
        if (insert > 0){

            RecruitmentEnterprise recruitmentEnterprise = recruitmentEnterpriseMapper.selectById(param.getCompanyRecruitAid());
            RecruitmentInfor recruitmentInfor = recruitmentInforMapper.selectById(recruitmentEnterprise.getRecuitmentaid());
            // 发送两条消息：一条是向公司推荐自己的消息；一条是发送自己的简历
            messageMapper.insert(new Message(){{
                setUserAid(user.getAid());
                setEnterpriseAid(recruitmentEnterprise.getEnterpriseaid());
                setContent("您好，我对贵司【" + recruitmentInfor.getPosition() + "】岗位很感兴趣，请您看一下我的简历，如果合适可以随时和我联系，谢谢。");
                setUserEnterprise(1);
                setEnterpriseUser(0);
                setIsRead(0);
            }});

            Message message = new Message();
            message.setUserAid(user.getAid());
            message.setEnterpriseAid(recruitmentEnterprise.getEnterpriseaid());
            message.setUserEnterprise(1);
            message.setEnterpriseUser(0);
            message.setIsRead(0);
            if (user.getResumeUrl() != null){
                message.setContent(user.getResumeUrl());
            }else {
                message.setContent("http-online-resume");
            }
            messageMapper.insert(message);
            return ResponseWrapper.markCustomSuccess("投递成功！");
        }else {
            return ResponseWrapper.markError();
        }
    }

    /**
     * 判断当前职位是否已经投递
     *
     * @param param 参数类
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper checkIsDeliver(DeliverResume param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        List<UserEnterpriseRecruit> userEnterpriseRecruits = userEnterpriseRecruitMapper.selectList(new LambdaQueryWrapper<UserEnterpriseRecruit>()
                .eq(UserEnterpriseRecruit::getUserAid, user.getAid())
                .eq(UserEnterpriseRecruit::getEnterpriseRecruitAid, param.getCompanyRecruitAid()));
        if (userEnterpriseRecruits.size() > 0){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 判断当前登陆的用户是否有投递记录
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper checkLoginUserIsHaveDeliverRecord(CheckLoginUserIsHaveDeliverRecord param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        List<UserEnterpriseRecruit> userEnterpriseRecruits = userEnterpriseRecruitMapper.selectList(new LambdaQueryWrapper<UserEnterpriseRecruit>()
                .eq(UserEnterpriseRecruit::getUserAid, user.getAid()));
        if (userEnterpriseRecruits.size() > 0){
            return ResponseWrapper.markSuccess(true);
        }else {
            return ResponseWrapper.markSuccess(false);
        }
    }

    /**
     * 查询当前登录用户的投递记录
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper queryLoginUserDeliverRecord(CheckLoginUserIsHaveDeliverRecord param) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        List<UserEnterpriseRecruit> userEnterpriseRecruits = userEnterpriseRecruitMapper.selectList(new LambdaQueryWrapper<UserEnterpriseRecruit>()
                .eq(UserEnterpriseRecruit::getUserAid, user.getAid())
                .orderByDesc(UserEnterpriseRecruit::getCreateTime));
        DeliverRecordResult result = new DeliverRecordResult();
        ArrayList<DeliverRecordResultItem> deliverRecordResults = new ArrayList<>();
        for (UserEnterpriseRecruit item : userEnterpriseRecruits) {

            DeliverRecordResultItem deliverRecordResultItem = new DeliverRecordResultItem();
            RecruitmentEnterprise recruitmentEnterprise = recruitmentEnterpriseMapper.selectById(item.getEnterpriseRecruitAid());
            RecruitmentInfor recruitmentInfor = recruitmentInforMapper.selectById(recruitmentEnterprise.getRecuitmentaid());
            deliverRecordResultItem.setPositionName(recruitmentInfor.getPosition());

            deliverRecordResultItem.setDeliverTime(ToolForDateTime.LocalDateTimeToStringToDate(item.getCreateTime()));

            if(recruitmentInfor.getRecruitmentAddress().length() > 2){
                deliverRecordResultItem.setRecruitAddress(recruitmentInfor.getRecruitmentAddress().substring(0,2));
            }else {
                deliverRecordResultItem.setRecruitAddress(recruitmentInfor.getRecruitmentAddress());
            }

            deliverRecordResultItem.setEducation(recruitmentInfor.getEducation());

            Enterprise enterprise = enterpriseMapper.selectById(recruitmentEnterprise.getEnterpriseaid());
            deliverRecordResultItem.setCompanyName(enterprise.getName());

            deliverRecordResultItem.setRecruitmentInfoAid(recruitmentEnterprise.getRecuitmentaid());
            deliverRecordResultItem.setCompanyAid(recruitmentEnterprise.getEnterpriseaid());
            deliverRecordResultItem.setCompanyAccount(enterprise.getAccountNumber());

            deliverRecordResults.add(deliverRecordResultItem);

        }
        result.setList(deliverRecordResults);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 通过userJobAid查询用户的简历信息
     *
     * @param param 参数
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper queryClickUserResume(QueryClickUserResume param) {
        UserJob userJob = userJobMapper.selectById(param.getUserJobAid());
        User user = userMapper.selectById(userJob.getUseraid());
        Resume resume = resumeMapper.selectById(user.getResumeAid());
        if (resume != null){
            return ResponseWrapper.markSuccess(resume);
        }else {
            return ResponseWrapper.markSuccess(null);
        }
    }
}
